package com.verify.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.verify.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptachaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private final static Long VALID_TIME=30*60*1000L;

    @RequestMapping("/getCaptcha" )
    public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {
        //生成验证码
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        //写出到浏览器（Servlet输出）
        //respone要写在最上面（使用之前）
        //不是每一个浏览器都能够帮我们自动解析，下面是解析成什么类型
        //设置图片类型

        long start =System.currentTimeMillis();
        response.setContentType("image/jpeg");
        //设置编码
        //一般情况下，这个处理是前端的
        response.setHeader("Progma","No-cahce");
        response.setCharacterEncoding("utf-8");
        try {
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            String code=captcha.getCode();
            session.setAttribute(captchaProperties.getSession().getKey(),code);
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());
            captcha.write(response.getOutputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
        long end=System.currentTimeMillis();
//        finally {
//            response.getOutputStream().close();
//            //自行关闭
//        }

        System.out.println("getCaptcha cost time:"+(end-start)+"ms");
    }

    //校验接口
    @RequestMapping("check")
    public boolean check(HttpSession session,String captcha){
        if(!StringUtils.hasLength(captcha)){
            return  false;
        }
        //验证验证码
        String code= (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date date= (Date) session.getAttribute(captchaProperties.getSession().getDate());
        //equalsIgnoreCase不区分大小写
        if(captcha.equalsIgnoreCase(code)&&System.currentTimeMillis()-date.getTime()<VALID_TIME){
            return true;
        }
        return false;
    }

}
